<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="js/jquery.qrcode.min.js"></script>
		<script type="text/javascript" src="js/html2canvas.min.js"></script>
		<script type="text/javascript" src="js/html2canvas.js"></script>
		<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
		 crossorigin="anonymous"></script>
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
		 crossorigin="anonymous">
		<title>html to img demo</title>
		<style type="text/css">
			.content_main {
				position: absolute;
				width: 80%;
				height: 80%;
				left: 10%;
				top: 10%;
				background: url('static/background.jpg') no-repeat center;
			}
			.content_list {
				position: relative;
				left: 70%;
				top: 5%;
				width: 300px;
				height: 300px;
			}
		</style>
	</head>
	<body>
		<div id="content_main" class="content_main">
			<div id="content_list" class="content_list">
				<li class="list-group-item"></li>
				<li class="list-group-item"></li>
				<li id="qrcode" class="list-group-item"></li>
				<li id="li_but" class="list-group-item">
					<button id="but" type="button" class="btn btn-danger"> 点击替换页面为图片 </button>
				</li>
			</div>
		</div>
	</body>

	<script type="text/javascript">
		// 模拟从后台获取的普通数据
		document.getElementsByTagName("li")[0].innerHTML = "巴拉涅卡尔维湾";
		document.getElementsByTagName("li")[1].innerHTML = "法国科西嘉岛";
		// 模拟从后台获取的二维码字符串 
		var code_url = "201801030400509";

		makeCode();
		/**
		 * 生成二维码图片
		 */
		function makeCode() {
			$("#qrcode").qrcode({
				correctLevel: 2, // 线条粗度
				render: "table", //table方式 
				width: 198, //宽度 
				height: 198, //高度 
				text: code_url //任意内容 
			});
		}
		
		/**
		 * 将指定区块生成图片 
		 */
		document.getElementById("but").onclick=function() {
			var imgContent = document.getElementById("content_main");
			let scale = window.devicePixelRatio // 获取设备像素比
			let width = imgContent.offsetWidth; // 获取dom 宽度
			let height = imgContent.offsetHeight; // 获取dom 高度

			// 两个参数：所需要截图的元素id，截图后要执行的函数， canvas为截图后返回的最后一个canvas
			html2canvas(imgContent, {
				allowTaint: true,
				useCORS: true,
				dpi: scale * 2,
				scale: scale,
				ignoreElements: (element)=>{
					if(element.id==='li_but'){
						return true;
					}
				}
			}).then(function(canvas) {
				document.body.innerHTML = "<div id='content_main2' class='content_main'></div>";
				document.getElementById("content_main2").appendChild(canvas);
				imgContent.remove();
			});
		}
	</script>
</html>
